package map.editor;

import gui.*;
import gui.user.User;
import images.ImageLoader;

import java.awt.*;
import java.awt.geom.AffineTransform;

import javax.swing.JFileChooser;
import javax.swing.JPanel;

import map.PlayingField;
import math.Vector2D;

public class View extends JPanel
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 5967305085281341823L;
	/**
	 * 
	 */

	private PlayingField pf;
	
	private Polygon cursor;
	
	private ImageLoader current;
	
	private User user;
	
	public View()
	{
		pf = new PlayingField( 10, 10 );
		
		current = PlayingField.tileG;
		
		cursor = new Polygon();
		cursor.addPoint( 16, 0 );
		cursor.addPoint( 32, 8 );
		cursor.addPoint( 16, 15 );
		cursor.addPoint( 0, 8 );
		
		user = new User();
		this.addMouseListener( new GUIMouseListener( user ) );
		this.addMouseMotionListener( new GUIMouseMotionListener( user ) );
	}
	
	
	public void setCurrentTile( ImageLoader il )
	{
		current = il;
	}
	
	public void paint( Graphics g )
	{
		Graphics2D g2d = (Graphics2D)g;
		g2d.setColor( Color.black );
		g2d.fillRect( 0, 0, this.getWidth(), this.getHeight() );
		pf.render( g2d );
		
		Vector2D mouse = PlayingField.fromWorldToWorldOnGrid( user.getMouseMove() );
		g2d.setTransform( AffineTransform.getTranslateInstance( mouse.getX() - cursor.getBounds().getWidth() / 2, mouse.getY() - cursor.getBounds().getHeight() / 2 ) );
		g2d.setColor( new Color( 255, 255, 255, 128 ) );
		g2d.fillPolygon( cursor );
		g2d.setTransform( new AffineTransform() );
	}
	
	public void update( double duration )
	{
		Vector2D mouse = user.getMousePos();
		if( mouse != null )
		{
			mouse = PlayingField.fromWorldToGrid( mouse );
			
			pf.getTile( mouse ).setImage( current );
			
			user.doneWithMouse();
		}
	}
	
	public void open()
	{
		JFileChooser chooser = new JFileChooser();
		int choice = chooser.showOpenDialog( this );
		
		if( choice == JFileChooser.APPROVE_OPTION )
		{
			pf = PlayingField.load( chooser.getSelectedFile().getPath() );
		}
	}
	
	public void save()
	{
		JFileChooser chooser = new JFileChooser();
		int choice = chooser.showSaveDialog( this );
		
		if( choice == JFileChooser.APPROVE_OPTION )
		{
			pf.save( chooser.getSelectedFile().getPath() );
		}
	}
}
